﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CacheEngine
{
    /// <summary>内存缓存</summary>
    public class MemoryCacheEngine : ICacheEngine
    {
        private static readonly IThreadSafeDictionary<string, CachedItem> CachedItems = new ThreadSafeDictionary<string, CachedItem>();

        /// <summary>根据关键字取得缓存数据</summary>
        /// <param name="key">关键字</param>
        /// <returns>缓存数据</returns>
        public T Get<T>(string key)
        {
            object returnVal = null;
            CachedItem cachedItem = null;

            if (CachedItems.TryGetValue(key, out cachedItem))
            {
                if (cachedItem.ExpirationDate > DateTime.Now)
                    returnVal = cachedItem.Item;
                else
                {
                    CachedItems.RemoveSafe(key);
                }
            }

            return (T)returnVal;
        }

        /// <summary>保存缓存数据</summary>
        /// <param name="key">关键字</param>
        /// <param name="itemToCache">缓存数据</param>
        /// <param name="expirationDate">过期时间</param>
        public void SaveOrUpdate(string key, object itemToCache, DateTime expirationDate)
        {
            var ci = new CachedItem();
           // ci.Item = itemToCache;
            ci.ExpirationDate = expirationDate;
            CachedItems.MergeSafe(key, ci);
        }

    }
}
